<!-- 验证码组件 -->
<template>
    <div class="verification-code-container">
        <div class="input-wrapper">
            <el-input v-model="inputCode" :placeholder="placeholder" :maxlength="6" clearable @input="handleInput">
            </el-input>
            <el-button type="primary" :disabled="isCounting" @click="handleGetCode" class="code-btn">
                {{ buttonText }}
            </el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Message } from '@element-plus/icons-vue'

const props = defineProps({
    // 倒计时时间（秒）
    seconds: {
        type: Number,
        default: 60
    },
    // 输入框占位符
    placeholder: {
        type: String,
        default: '请输入验证码'
    },
    // 按钮文字
    buttonText: {
        type: String,
        default: '获取验证码'
    }
})

const emit = defineEmits(['get-code', 'update:modelValue'])

const inputCode = ref('')
const countdown = ref(0)
let timer = null

// 计算属性：按钮显示文本
const buttonText = computed(() => {
    return isCounting.value ? `${countdown.value}s后重新获取` : props.buttonText
})

// 计算属性：是否正在倒计时
const isCounting = computed(() => countdown.value > 0)

// 处理输入事件
const handleInput = (value) => {
    emit('update:modelValue', value)
}

// 触发获取验证码
const handleGetCode = async () => {
    try {
        // 触发父组件获取验证码逻辑
        await emit('get-code')
        startCountdown()
    } catch (error) {
        ElMessage.error('获取验证码失败')
    }
}

// 开始倒计时
const startCountdown = () => {
    countdown.value = props.seconds
    timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--
        } else {
            clearInterval(timer)
        }
    }, 1000)
}

// 组件卸载时清除定时器
onUnmounted(() => {
    if (timer) clearInterval(timer)
})

// 暴露方法给父组件
defineExpose({
    resetCountdown: () => {
        countdown.value = 0
        if (timer) clearInterval(timer)
    }
})
</script>

<style scoped>
.verification-code-container {
    display: flex;
    align-items: center;
}

.input-wrapper {
    display: flex;
    gap: 10px;
    width: 100%;
}

.code-btn {
    white-space: nowrap;
}

.el-input {
    flex: 1;
}
</style>
